package cn.qinhao.pethome.shop.service.impl;

import cn.qinhao.pethome.basic.base.BaseConstants;
import cn.qinhao.pethome.basic.base.service.impl.BaseServiceImpl;
import cn.qinhao.pethome.basic.exception.BusinessException;
import cn.qinhao.pethome.basic.until.BaiduAuditUtils;
import cn.qinhao.pethome.basic.until.MD5Utils;
import cn.qinhao.pethome.basic.until.StrUtils;
import cn.qinhao.pethome.employee.domain.Employee;
import cn.qinhao.pethome.employee.service.IEmployeeService;
import cn.qinhao.pethome.shop.domain.*;
import cn.qinhao.pethome.shop.mapper.ShopAuditLogMapper;
import cn.qinhao.pethome.shop.mapper.ShopMapper;
import cn.qinhao.pethome.shop.service.IShopService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author qinhao
 * @since 2023-02-23
 */
@Service
public class ShopServiceImpl extends BaseServiceImpl<Shop> implements IShopService {
    @Autowired
    private IEmployeeService employeeService;
    @Autowired//用于下面的同名逻辑校验
    private ShopMapper shopMapper;
    @Autowired
    private ShopAuditLogMapper shopAuditLogMapper;
    @Autowired//邮件的固定写法
    private JavaMailSender javaMailSender;
    @Override
    public void add(Shop shop) {


        //店铺注入数据（店铺字段里面已经有了基本对应的的字段，而需求页面只有三个字段）
        //做店铺数据校验
        shopVerification(shop);
        //补充数据  注册时间 审核状态
        shop.setRegisterTime(new Date());//当前注册时间
        shop.setState(BaseConstants.Shop.STATE_WAIT_AUTID);//待审核

        //添加管理员信息  注入员工对象
        Employee employee = shop.getEmployee();
        //员工做数据校验 ctrl+alt+m选中需要生成的方法，快捷键一键提取方法
        employeeVerification(employee);
        //补充员工数据
        employee.setAge(20);
        String salt = StrUtils.getComplexRandomString(32);
        employee.setSalt(salt);
        //密码加密加盐,顺序什么顺序存，就什么顺序取
        //String pwd = MD5Utils.encrypByMd5(employee.getPassword()+salt);
        employee.setPassword(MD5Utils.encrypByMd5(employee.getPassword()+salt));
        employee.setDepartmentId(1L);
        employee.setState(BaseConstants.Employee.STATE_NORMAL);//状态
        employeeService.add(employee);
        //补充数据还差一个员工的id,employee.getId()通过mapper里面的主键回填获得
        shop.setAdminId(employee.getId());
        //添加店铺
        super.add(shop);
        //管理员还有一个shop的id需要补充,同理也是通过主键回填
        employee.setShopId(shop.getId());
        //设置完后要修改对象,因为员工也返回了主键id，所以要修改员工对象
        employeeService.update(employee);
        //1、先保存员工 2、再保存店铺 3、最后修改员工——》都修改了店铺和员工的id进行修改，等价于把两个数据关联上
    }

    private void employeeVerification(Employee employee) {
        //员工做数据校验，使用的自定义异常BusinessException
        if(employee.getUsername()==null){
            throw new BusinessException("账户名不能为空");
        }
        if(employee.getPhone()==null){
            throw new BusinessException("手机号码不能为空");
        }
        if(employee.getEmail()==null){
            throw new BusinessException("电子邮件不能为空");
        }
        if(employee.getPassword()==null){
            throw new BusinessException("密码不能为空");
        }
    }

    private void shopVerification(Shop shop) {
        //店铺做数据校验  使用的自定义异常BusinessException
        if(shop.getName()==null){
            throw new BusinessException("店铺名不能为空");
        }
        if(shop.getTel()==null){
            throw new BusinessException("电话不能为空");
        }
        if(shop.getAddress()==null){
            throw new BusinessException("店铺地址不能为空");
        }
        //处理店铺名敏感词逻辑
        Boolean aBoolean = BaiduAuditUtils.TextCensor(shop.getName());
        if(!aBoolean){
            throw new BusinessException("店铺名不合规，请更换");
        }
        //处理业务逻辑  店铺名不能重复——通过传入的店铺名去数据库查询进行比对
        Shop byShopName = shopMapper.findByShopName(shop.getName());
        if (byShopName!=null){
            throw new BusinessException("店铺名已经存在，请更换");
        }
    }

    @Override//ShopVo专门用来返回数据 和 接收前端的数据
    public void success(ShopVo shopVo) {
        //修改状态
        Shop shop = shopMapper.selectOne(shopVo.getId());
        shop.setState(BaseConstants.Shop.STATE_WAIT_ACTIVE);
        shopMapper.update(shop);
        //添加审核日志内容
        ShopAuditLog shopAuditLog = new ShopAuditLog();
        shopAuditLog.setAuditTime(new Date());
        shopAuditLog.setShopId(shopVo.getId());
        shopAuditLog.setNote(shopVo.getNote());
        shopAuditLog.setAuditId(2L);//随便写的，因为登录逻辑还没有实现
        shopAuditLog.setState(BaseConstants.Shop.STATE_WAIT_ACTIVE);
        shopAuditLogMapper.add(shopAuditLog);
        try {
            //创建复杂邮件对象
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            //发送复杂邮件的工具类
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "utf-8");
            helper.setFrom("1351586651@qq.com");
            helper.setSubject("审核通过，待激活");
            //第二个参数 true 代表是否是一个html内容
            helper.setText("<h1>审核成功</h1>" +
                    "<p><a href='http://127.0.0.1:8080/shop/activate/"+shopVo.getId()+"'>点击激活</a></p>", true);
            //添加附件 <a href = "http://www.baidu.com">点击这里</a>
            helper.addAttachment("文件名.jpg", new File("E:\\java\\知识点回顾\\resources\\24.jpg"));
            helper.addAttachment("压缩文件", new File("E:\\java\\知识点回顾\\resources\\压缩包.zip"));
            //收件人
            helper.setTo("1351586651@qq.com");
            //发送邮件
            javaMailSender.send(mimeMessage);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void reject(ShopVo shopVo) {
        //修改状态
        Shop shop = shopMapper.selectOne(shopVo.getId());
        shop.setState(BaseConstants.Shop.STATE_REJECT_AUDIT);
        shopMapper.update(shop);
        //添加审核日志内容
        ShopAuditLog shopAuditLog = new ShopAuditLog();
        shopAuditLog.setAuditTime(new Date());
        shopAuditLog.setShopId(shopVo.getId());
        shopAuditLog.setNote(shopVo.getNote());
        shopAuditLog.setAuditId(3L);//随便写的，因为登录逻辑还没有实现
        shopAuditLog.setState(BaseConstants.Shop.STATE_REJECT_AUDIT);
        shopAuditLogMapper.add(shopAuditLog);
        try {
            //创建复杂邮件对象
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            //发送复杂邮件的工具类
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "utf-8");
            helper.setFrom("1351586651@qq.com");
            helper.setSubject("审核不通过");
            //第二个参数 true 代表是否是一个html内容
            helper.setText("<h1>驳回</h1>" +
                    "<img src='https://p0.ssl.img.360kuai.com/t0169a0e58e0c2a5f4e.webp' />",true);
            //添加附件
            helper.addAttachment("文件名.jpg", new File("E:\\java\\知识点回顾\\resources\\24.jpg"));
            helper.addAttachment("压缩文件", new File("E:\\java\\知识点回顾\\resources\\压缩包.zip"));
            //收件人
            helper.setTo("1351586651@qq.com");
            //发送邮件
            javaMailSender.send(mimeMessage);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }
    //激活
    @Override
    public void activate(Long id) {
        //修改状态
        Shop shop = shopMapper.selectOne(id);
        shop.setState(BaseConstants.Shop.STATE_ACTIVE_SUCCESS);
        shopMapper.update(shop);
        //添加审核日志内容
        ShopAuditLog shopAuditLog = new ShopAuditLog();
        shopAuditLog.setAuditTime(new Date());
        shopAuditLog.setShopId(id);
        shopAuditLog.setAuditId(4L);//随便写的，因为登录逻辑还没有实现
        shopAuditLog.setState(BaseConstants.Shop.STATE_ACTIVE_SUCCESS);
        shopAuditLogMapper.add(shopAuditLog);
    }
    //饼图逻辑
    @Override
    public ShopPicEchartsVo pieEcharts() {
        //创建一个返回数据的对象
        ShopPicEchartsVo shopPicEchartsVo = new ShopPicEchartsVo();
        //设置饼图的标题
        shopPicEchartsVo.setTitle("店铺的状态");
        List<String> list = new ArrayList<>();
        list.add("待审核");
        list.add("审核通过");
        list.add("激活成功");
        list.add("驳回");
        //设置饼图的副标题，就是左边的小方块提示
        shopPicEchartsVo.setLegendData(list);
        //根据前端数据格式构建数据，构建好的数据放入到集合中合并，最后添加到真实数据中返回
        List<Object> listObj = new ArrayList<>();
        //获取数据库查出的数据源
        List<ShopDo> shopDos = shopMapper.pieEcharts();
        //遍历集合获取状态和常量工具类比较，看属于哪一个状态
        for (ShopDo shopDo : shopDos) {
            if(BaseConstants.Shop.STATE_WAIT_AUTID == shopDo.getState()){
                Map<String,Object> data = new HashMap<>();
                data.put("name","待审核");
                data.put("value",shopDo.getNum());
                //把添加到map中的数据添加到返回数据的集合中
                listObj.add(data);
            }
            if(BaseConstants.Shop.STATE_WAIT_ACTIVE == shopDo.getState()){
                Map<String,Object> data = new HashMap<>();
                data.put("name","审核通过");
                data.put("value",shopDo.getNum());
                listObj.add(data);
            }
            if(BaseConstants.Shop.STATE_ACTIVE_SUCCESS == shopDo.getState()){
                Map<String,Object> data = new HashMap<>();
                data.put("name","激活成功");
                data.put("value",shopDo.getNum());
                listObj.add(data);
            }
            if(BaseConstants.Shop.STATE_REJECT_AUDIT == shopDo.getState()){
                Map<String,Object> data = new HashMap<>();
                data.put("name","驳回");
                data.put("value",shopDo.getNum());
                listObj.add(data);
            }
        }
        //设置真正的数据返回前端，最后前端通过返回的数据打印看结构赋值即可
        shopPicEchartsVo.setData(listObj);
        return shopPicEchartsVo;
    }
    //柱状图
    @Override
    public ShopColumnchartVo ColumnEcharts() {
        ShopColumnchartVo shopColumnchartVo = new ShopColumnchartVo();
        List<String> list = new ArrayList<>();
        list.add("审核通过");
        list.add("激活成功");
        list.add("驳回");
        list.add("待审核");
        shopColumnchartVo.setXData(list);
    //设置真实的数据
        List<Long> totals = new ArrayList<>();
        List<ShopDo> shopDos = shopMapper.pieEcharts();
        for (ShopDo shopDo : shopDos) {
            if(BaseConstants.Shop.STATE_WAIT_AUTID == shopDo.getState()){
                totals.add(shopDo.getNum());
            }
            if(BaseConstants.Shop.STATE_WAIT_ACTIVE == shopDo.getState()){
                totals.add(shopDo.getNum());
            }
            if(BaseConstants.Shop.STATE_ACTIVE_SUCCESS == shopDo.getState()){
                totals.add(shopDo.getNum());
            }
            if(BaseConstants.Shop.STATE_REJECT_AUDIT == shopDo.getState()){
                totals.add(shopDo.getNum());
            }
        }
        shopColumnchartVo.setData(totals);
        return shopColumnchartVo;
    }
}
